package com.piggy.sys.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.BooleanUtil;
import com.piggy.common.core.constant.UserConstants;
import com.piggy.common.core.utils.StringUtils;
import com.piggy.common.core.web.controller.BaseController;
import com.piggy.common.log.annotation.Log;
import com.piggy.common.log.enums.BusinessType;
import com.piggy.common.satoken.annotation.Inner;
import com.piggy.common.satoken.utils.SecurityUtils;
import com.piggy.common.core.domain.R;
import com.piggy.sys.api.domain.SysDept;
import com.piggy.sys.domain.vo.TreeSelect;
import com.piggy.sys.service.ISysDeptService;
import org.apache.commons.lang3.ArrayUtils;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 部门信息
 *
 * @author shark
 */
@RestController
@RequestMapping("/dept")
public class SysDeptController extends BaseController {
    @Resource
    private ISysDeptService deptService;

    /**
     * 获取部门列表
     */
    //@SaCheckPermission("system:dept:list")
    @GetMapping("/list")
    public R list(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return R.ok(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    //@SaCheckPermission("system:dept:list")
    @GetMapping("/list/exclude/{deptId}")
    public R excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext()) {
            SysDept d = (SysDept) it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")) {
                it.remove();
            }
        }
        return R.ok(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    //@SaCheckPermission("system:dept:query")
    @GetMapping(value = "/{deptId}")
    public R getInfo(@PathVariable Long deptId) {
        return R.ok(deptService.selectDeptById(deptId));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public R<List<TreeSelect>> treeselect(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return R.ok(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public R roleDeptTreeselect(@PathVariable("roleId") Long roleId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Map<String, Object> ajax = new HashMap<>(2);
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.buildDeptTreeSelect(depts));
        return R.ok(ajax);
    }
    /**
     * 获取组织类型
     */
    @Inner
    @GetMapping(value = "/getOrgType")
    public Integer getOrgType(@RequestParam("deptId") Long deptId,@RequestParam("sceneKey") String sceneKey) {
        return deptService.getOrgType(deptId,sceneKey);
    }


    /**
     * 获取组织类型id
     */
    @Inner
    @GetMapping(value = "/getOrgDeptId/{deptId}")
    public Long getOrgDeptId(@PathVariable("deptId") Long deptId) {
        return deptService.getOrgDeptId(deptId);
    }


    /**
     * 获取组织类型id
     */
    @Inner
    @GetMapping(value = "/getDeptListByOrgType")
    public R getDeptListByOrgType(@RequestParam("sceneKey") String sceneKey, @RequestParam("busineseType") Integer busineseType) {
        return R.ok(deptService.getDeptListByOrgType(sceneKey,busineseType));
    }

    /**
     * 新增部门
     */
    //@SaCheckPermission("system:dept:add")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody SysDept dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return R.fail("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(SecurityUtils.getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    //@SaCheckPermission("system:dept:edit")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody SysDept dept) {
        if (BooleanUtil.toBoolean(deptService.checkDeptNameUnique(dept))) {
            return R.fail("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(dept.getDeptId())) {
            return R.fail("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0) {
            return R.fail("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    //@SaCheckPermission("system:dept:remove")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public R remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return R.fail("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return R.fail("部门存在用户,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }

    @Inner
    @PostMapping("/queryDeptAll")
    public R<List<SysDept>> queryDeptAll() {
        return R.ok(deptService.queryDeptAll());
    }


    @Inner
    @GetMapping("/getById")
    public R<SysDept> getById(@RequestParam Long deptId){
        return R.ok(deptService.selectDeptById(deptId));
    }

    /**
     * 新增部门
     */
    @Inner
    @PostMapping(value = "/saveSysDept")
    public R<SysDept> saveSysDept(@RequestBody SysDept sysDept) {
        deptService.saveOrUpdate(sysDept);
        return R.ok(sysDept);
    }

    /**
     * 获取部门树列表
     */
    //("system:user:list")
    //@SaCheckPermission("system:dept:list")
    @GetMapping("/deptTree")
    public R<List<TreeSelect>> deptTree(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return R.ok(deptService.buildDeptTreeSelect(depts));
    }

}
